<template>
  <d2-container>
	  <template slot="header">
		  <el-button type="primary" @click="change">新 增</el-button>
		  <el-button type="primary" plain style="margin-bottom: 5px" @click="openRole" >授 权</el-button>
	  </template>
   <template>

      <el-table stripe border
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            fixed
            prop="userName"
            label="用户名"
            width="150">
          </el-table-column>
          <el-table-column
            fixed
            prop="realName"
            label="姓名"
            width="140">
          </el-table-column>
          <el-table-column
            prop="nickName"
            label="昵称" >
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱" >
          </el-table-column>
          <el-table-column
            prop="isRoot"
            label="是否超级管理员"
            width="150"
            :filters="[{ text: '否', value: 0 }, { text: '是', value: 1 }]"
            :filter-method="filterIsRoot"
            filter-placement="bottom-end">
            <template slot-scope="scope">
            <el-tag
              :type="scope.row.isRoot === 1 ? 'primary' : 'success'"
              disable-transitions>{{scope.row.isRoot==0?"否":"是"}}</el-tag>
          </template>
          </el-table-column>
          <el-table-column
            prop="phone"
            label="手机">
          </el-table-column>
          <el-table-column
            prop="departmentName"
            label="部门名称">
          </el-table-column>
          <!-- <el-table-column
            prop="birthday"
            label="Birthday" :formatter="forBirthday">
          </el-table-column> -->
          <el-table-column
            prop="createTime"
            label="创建时间" :formatter="forDate">
          </el-table-column>
          <!-- <el-table-column
            prop="birthday"
            label="Birthday" :formatter="forBirthday">
          </el-table-column> -->
          <el-table-column
            fixed="right"
            label="操作"
            width="180">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="updateRow(scope.row.id)">编辑</el-button>
              <el-button
                @click.native.prevent="deleteRow(scope.$index, tableData)"
                size="small">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

    </template>
    <template>
      <div>
          <keep-alive>
              <addPage :addPage="addComponent" @on-addPage-change="onAddPageChange" @on-loadlist-change="fetchData" ></addPage>
            </keep-alive>
      </div>
      <div>
          <keep-alive>
              <updatePage @on-loadlist-change="fetchData"  :uShow="updateComponent" @on-uShow-change="onUShowChange" :uId="updateId" @on-id-change="onIdChange"></updatePage>
            </keep-alive>
      </div>
    </template>
    <template slot="footer">

      <div class="page">
        <el-pagination
		  background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50,100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </template>

    <template>
          <el-dialog title="授权" :visible.sync="roleDisplay" :before-close="handleClose">
          <el-main>
                <el-table
                    :data="roleTableData"
                    style="width: 100%" ref="roleTable"
                    @selection-change="handleSelectionChangeRole">
                    <el-table-column
                      type="selection">
                    </el-table-column>
                    <el-table-column
                    prop="roleName"
                    label="角色名称">
                  </el-table-column>
                </el-table>
          </el-main>
          <el-footer>
             <el-button type="primary" @click="submitAuthRole">确 定</el-button>
             <el-button @click="roleDisplay=false">取 消</el-button>
           </el-footer>
        </el-dialog>
    </template>
  </d2-container>
</template>

<script>
import { UserList, DelUser, GetAllRole, AuthUseru, FindByUserId } from '@api/user/user'
import addPage from './add'
import updatePage from './update'
import dayjs from 'dayjs'
export default {
  name: 'system-user',
  components: {
    addPage, updatePage
  },
  data () {
    return {
      addComponent: false,
      updateComponent: false,
      roleDisplay: false,
      updateId: 0,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      multipleSelection: [],
      multipleSelectionRole: [],
      roleTableData: []
    }
  },

  mounted () {
    this.fetchData()
  },
  methods: {
    /** 双向绑定 start */
    change () {
      this.addComponent = !this.addComponent
    },
    onAddPageChange (val) {
      this.addComponent = val// ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    uChange () {
      this.updateComponent = !this.updateComponent
    },
    onUShowChange (val) {
      this.updateComponent = val// ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    idChange (val) {
      this.updateId = val
    },
    onIdChange (val) {
      this.updateId = val// ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    /** 双向绑定 end */

    fetchData () {
      this.loading = true
      UserList({
        currentPage: this.currentPage, pageSize: this.pageSize
      }).then(res => {
        // console.log(res)
        this.tableData = res.data.content
        this.total = res.data.total
        this.loading = false
      }).catch(err => {
        console.log('err', err)
        this.loading = false
      })
    },
    handleSizeChange (val) {
      //  console.log(`每页 ${val} 条`);
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val
      this.fetchData()
    },
    deleteRow (index, rows) {
      // console.log( rows[index].id)
      // rows.splice(index, 1)

      this.$confirm('确定删除吗').then(() => {
        let id = rows[index].id
        this.loading = true
        DelUser({ userId: id }).then(res => {
          this.fetchData()
          this.loading = false
        }).catch(err => {
          console.log('err', err)
          this.loading = false
        }) // function(done)，done 用于关闭 Dialog
        done()
      }).catch(() => {
        // console.log("取消操作");
      })
    },
    filterIsRoot (value, row) {
      return row.isRoot === value
    },
    updateRow (id) {
      this.uChange()
      this.idChange(id)
    },
    // forBirthday(row, column){
    //   return row.birthday==null?"":dayjs(row.birthday).format('YYYY-MM-DD')
    // },
    forDate (row, column) {
      return row.createTime == null ? '' : dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    // 复选框选择赋值
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 功能授权 窗口 关闭
    handleClose (done) {
      this.$confirm('确定关闭吗').then(() => {
        // function(done)，done 用于关闭 Dialog
        done()
      }).catch(() => {
        // console.log("点击确定时触发");
      })
    },
    openRole () {
      if (this.multipleSelection.length == 1) {
        this.loading = true
        this.multipleSelectionRole = []
        this.roleTableData = []
        GetAllRole().then(res => {
          this.roleTableData = res.data

          this.loadRoleSelect()
          this.loading = false
        }).catch(err => {
          console.log('err', err)
          this.loading = false
        })
        this.roleDisplay = true
      } else {
        this.$message({
          message: '请选择单项进行授权',
          type: 'warning'
        })
      }
    },
    submitAuthRole () {
      this.loading = true
      let roles = []
      let users = []
      this.multipleSelection.forEach(function (e) {
        users.push(e.id)
      })
      this.multipleSelectionRole.forEach(function (e) {
        roles.push(e.id)
      })
      AuthUseru({ roleIds: roles, userIds: users }).then(res => {
        this.$message({
          message: '授权成功',
          type: 'success'
        })
        this.loading = true
        // this.roleDisplay=true
        this.roleDisplay = false
      }).catch(err => {
        console.log('err', err)
        this.loading = false
      })
    },
    handleSelectionChangeRole (val) {
      this.multipleSelectionRole = val
    }, // 加载已经分配的权限
    loadRoleSelect () {
      this.loading = true
      let this_ = this
      FindByUserId({ userId: this.multipleSelection[0].id + '' }).then(res => {
        this.multipleSelectionRole = []
        // console.info(JSON.stringify(res))
        this.$refs.roleTable.clearSelection()
        this.roleTableData.forEach(row => {
          res.data.forEach(e => {
            // console.info(row.id +" | "+ e.id)
            if (row.id === e.id) {
              this_.$refs.roleTable.toggleRowSelection(row)
            }
          })
        })
        this.loading = false
      }).catch(err => {
        console.log('err', err)
        this.loading = false
      })
    }
  }
}
</script>
